// scripts/postbuild.js
import { readFileSync, writeFileSync } from 'fs';
import { dirname, join, relative } from 'path';
import { fileURLToPath } from 'url';

// 获取当前模块的目录路径
const __dirname = dirname(fileURLToPath(import.meta.url));

const packages = ['core', 'layout'];

packages.forEach((pkgName) => {
  try {
    // 构造文件路径
    const srcPkgPath = join(__dirname, `../packages/${pkgName}/package.json`);
    const buildPkgPath = join(__dirname, `../packages/${pkgName}/package.build.json`);
    const destPath = join(__dirname, `../dist/${pkgName}/package.json`);

    // 读取原始 package.json
    const originalPkg = JSON.parse(readFileSync(srcPkgPath, 'utf8'));
    
    // 读取构建配置 (如果存在)
    let buildPkg = {};
    try {
      buildPkg = JSON.parse(readFileSync(buildPkgPath, 'utf8'));
    } catch (e) {
      console.log(`No package.build.json found for ${pkgName}, using defaults`);
    }

    // 准备最终 package.json 内容
    const finalPkg = {
      name: originalPkg.name,
      version: originalPkg.version,
      description: originalPkg.description,
      main: './' + relative(
        join(__dirname, `../packages/${pkgName}/dist`),
        join(__dirname, originalPkg.main)
      ).replace(/\\/g, '/'),
      module: './' + relative(
        join(__dirname, `../packages/${pkgName}/dist`),
        join(__dirname, originalPkg.module)
      ).replace(/\\/g, '/'),
      types: './' + relative(
        join(__dirname, `../packages/${pkgName}/dist`),
        join(__dirname, originalPkg.types || `../packages/${pkgName}/dist/index.d.ts`)
      ).replace(/\\/g, '/'),
      files: ['**/*'],
      scripts: {},
      dependencies: originalPkg.dependencies || {},
      peerDependencies: originalPkg.peerDependencies || {},
      ...buildPkg
    };

    // 写入 dist 目录
    writeFileSync(destPath, JSON.stringify(finalPkg, null, 2), 'utf8');
    console.log(`Successfully generated package.json for ${pkgName} in dist`);
  } catch (error) {
    console.error(`Error processing ${pkgName}:`, error.message);
    process.exit(1);
  }
});